package com.twotiger.and.activity;

import java.util.HashMap;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Message;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ProgressBar;
import app.twotiger.p2p.R;
import cn.jpush.android.api.JPushInterface;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.twotiger.and.Constants;
import com.twotiger.and.activity.base.BaseActivity;
import com.twotiger.and.activity.base.BaseHandler;
import com.twotiger.and.activity.project.ExperienceInverstConfirmPage;
import com.twotiger.and.activity.project.InverstInputAmountPage;
import com.twotiger.and.activity.project.ProjectDetailPage;
import com.twotiger.and.activity.user.LoginPage;
import com.twotiger.and.bean.Basebean;
import com.twotiger.and.bean.BroswerUrl;
import com.twotiger.and.bean.ExperienceOrder;
import com.twotiger.and.bean.Jpushbean2;
import com.twotiger.and.bean.Order;
import com.twotiger.and.bean.ProjectdetailData;
import com.twotiger.and.bean.Share;
import com.twotiger.and.util.LogUtil;
import com.twotiger.and.util.PromptManager;
import com.twotiger.and.util.PromptManager.ReChargeClickListener;
import com.twotiger.and.util.StringUtils;
import com.twotiger.and.util.Tools;
import com.twotiger.and.util.UmShearUtils;
import com.twotiger.and.view.CusWebView;
import com.twotiger.and.web.JavaScriptInterface;
import com.twotiger.and.web.JavaScriptInterfaceForDialog;
import com.umeng.analytics.MobclickAgentJSInterface;

/**
 * webView
 * @Description: TODO(这里描述这个类的作用) 
 * @Author gao
 * @Date 2015年8月18日 下午8:59:58
 */
public class WebViewDialogPage extends BaseActivity {

    public static final int GOTO_BOUTIQUEPAGE = 1;
    public static final int GOTO_PROJECTEPAGE = 2;
    public static final int GOTO_ACCOUNTEPAGE = 3;
    public static final int GOTO_MOREPAGE = 4;
    public static final int TO_SHARE = 5;
    private static final int GETDETAILSUCCES = 6;
    private static final int GETDETAILFAIL = 7;
    protected static final int OPENPAYMENTSUCCES = 8;
    protected static final int OPENPAYMENTFAIL = 9;

    private CusWebView wv_dialog;
    private String errorHtml = "";
    private ProgressBar web_dialog_progressbar;
    private HashMap<String, String> params;
    public boolean isFinish;//JavaScriptinterfaceForDialog 中会控制isFinish
    private Button btn_finish;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
        case R.id.btn_finish:
            finish();
            overridePendingTransition(R.anim.fade_in_anim, R.anim.fade_out_anim);
            break;

        default:
            break;
        }
    }

    @Override
    protected void setListener() {
        handler = new BaseHandler(this) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case TO_SHARE:
                    Share mShare = (Share) msg.obj;
                    String title = mShare.getTitle();
                    String content = mShare.getContent();
                    String url = mShare.getUrl();
                    String pic = mShare.getPic();
                    UmShearUtils.shear(WebViewDialogPage.this, url, true, title, content, pic);
                    break;
                case GOTO_BOUTIQUEPAGE: //js调用跳精选页
                    startNewActivity(
                        new Intent(WebViewDialogPage.this, HomeActivity.class).putExtra("BUTTON",
                            R.id.radio_btn1), R.anim.push_left_in, R.anim.push_left_out, true);
                    break;
                case GOTO_PROJECTEPAGE: //js调用跳列表
                    startNewActivity(
                        new Intent(WebViewDialogPage.this, HomeActivity.class).putExtra("BUTTON",
                            R.id.radio_btn2), R.anim.push_left_in, R.anim.push_left_out, true);
                    break;
                case GOTO_ACCOUNTEPAGE: //js调用跳我的钱页
                    startNewActivity(
                        new Intent(WebViewDialogPage.this, HomeActivity.class).putExtra("BUTTON",
                            R.id.radio_btn3), R.anim.push_left_in, R.anim.push_left_out, true);
                    break;
                case GOTO_MOREPAGE: //js调用跳更多页
                    startNewActivity(
                        new Intent(WebViewDialogPage.this, HomeActivity.class).putExtra("BUTTON",
                            R.id.radio_btn4), R.anim.push_left_in, R.anim.push_left_out, true);
                    break;
                case GETDETAILSUCCES:
                    Basebean result = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result.isOk()) {
                        ProjectdetailData proData = JSON.parseObject(result.data,
                            ProjectdetailData.class);
                        if (Constants.TYPE_NID_ZHITOU.equals(proData.getType())) { //直投类型需跳到直投的投资页面
                            if (proData.getStatus() != Constants.PRO_STATUS_TRADING) { //项目不是募集中则  不能投资则跳到详情页面
                                Intent intent = new Intent(WebViewDialogPage.this,
                                    ProjectDetailPage.class).putExtra("PROJECT_ID",
                                    proData.getProjectId()).putExtra("MODE", proData.getMode());
                                startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out,
                                    false);
                                return;
                            }
                            if (!isLogin()) {
                                Intent intent = new Intent(WebViewDialogPage.this, LoginPage.class)
                                    .putExtra("FROM", R.id.to_inverst);
                                startNewActivity(intent, R.anim.slide_in_from_bottom,
                                    R.anim.silent_anim, false);
                                return;
                            }
                            if (!hasOpenThirdAct()) {
                                PromptManager.showConfirmAlertCommon(WebViewDialogPage.this,
                                    0, "", "您还未开通汇付天下托管账号，继续开通", "取消", "继续", true,
                                    new ReChargeClickListener() {

                                        @Override
                                        public void onClickConfirm() {

                                        }

                                        @Override
                                        public void onClickCancel() {
                                            // 确认，则继续
                                            openpayment();
                                        }
                                    });
                                return;
                            }
                            if (Constants.PRO_TYPE_NEWER.equals(proData.getMode())) { //新手项目老手不能进入投资页，只能看详情
                                if (!isNewMan()) {
                                    showToast("新手项目仅限第一次投资");
                                    return;
                                }
                            }
                            if (proData.getAmount() != 0) {

                                Order order = createOrder(proData);

                                Intent intent = new Intent(mContext, InverstInputAmountPage.class)
                                    .putExtra("ORDER", order);
                                startNewActivity(intent, R.anim.slide_in_from_bottom,
                                    R.anim.silent_anim, false);

                            }
                        } else if (Constants.TYPE_NID_HEIDONG.equals(proData.getType())) { //黑洞类型需跳到黑洞的投资页面
                            if (!isLogin()) {
                                Intent intent = new Intent(WebViewDialogPage.this, LoginPage.class)
                                    .putExtra("FROM", R.id.to_inverst);
                                startNewActivity(intent, R.anim.slide_in_from_bottom,
                                    R.anim.silent_anim, false);
                                return;
                            }
                            if (!hasOpenThirdAct()) {
                                PromptManager.showConfirmAlertCommon(WebViewDialogPage.this,
                                    0, "", "您还未开通汇付天下托管账号，继续开通", "取消", "继续", true,
                                    new ReChargeClickListener() {

                                        @Override
                                        public void onClickConfirm() {

                                        }

                                        @Override
                                        public void onClickCancel() {
                                            // 确认，则继续
                                            openpayment();
                                        }
                                    });
                                return;
                            }
                            if (!isNewManForWYTYJ()) {
                                showToast("体验金项目仅限未投资用户参与");
                                return;
                            }

                            //进入投资确认页面，将订单信息传过去
                            ExperienceOrder mExperienceOrder = createExperienceOrder(proData);

                            Intent intent = new Intent(mContext, ExperienceInverstConfirmPage.class)
                                .putExtra("ORDER", mExperienceOrder);
                            startNewActivity(intent, R.anim.slide_in_from_bottom,
                                R.anim.silent_anim, false);
                        }
                    } else {
                        showToast(result.codeDesc);
                    }
                    break;
                case GETDETAILFAIL:
                    showToast("网络异常");
                    break;
                case OPENPAYMENTSUCCES:
                    Basebean result_open = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_open.isOk()) {
                        BroswerUrl responseinfo = JSONObject.parseObject(result_open.data,
                            BroswerUrl.class);
                        Intent intent = new Intent(WebViewDialogPage.this, WebViewPage.class);
                        intent.putExtra("title", "开通三方托管账户");
                        intent.putExtra("url", responseinfo.getUrl());
                        intent.putExtra("BUSINESS_TYPE", WebViewPage.TYPE_PAYMENT_REGIST);
                        startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out,
                            isFinish);
                    }
                    break;
                case OPENPAYMENTFAIL:
                    showToast("网络异常");
                    break;
                default:
                    break;
                }
                super.handleMessage(msg);
            }
        };

        btn_finish.setOnClickListener(this);
    }

    /**
     * 创建体验金订单类
     * 
     * @param proData
     */
    protected ExperienceOrder createExperienceOrder(ProjectdetailData proData) {
        ExperienceOrder mExperienceOrder = new ExperienceOrder();
        mExperienceOrder.setProjectid(proData.getProjectId());
        mExperienceOrder.setProjectname(proData.getName());
        mExperienceOrder.setProject_yield(proData.getYield());
        mExperienceOrder.setRecyle(proData.getPeriod());
        mExperienceOrder.setRepaymenttype(proData.getRepayTypeName());
        mExperienceOrder.setStartyidtime(proData.getStartInterestDate()); //起息时间
        mExperienceOrder.setStartrepytime(proData.getEndInterestDate()); //还款时间
        mExperienceOrder.setMinInvest(proData.getMinInvest());
        mExperienceOrder.setMaxInvest(proData.getMaxInvest());
        mExperienceOrder.setInverstamount(proData.getValuation());

        mExperienceOrder.setType(proData.getType());
        mExperienceOrder.setMode(proData.getMode());

        mExperienceOrder.setRepayAmount(proData.getRepayAmount()); //用户实付金额

        return mExperienceOrder;
    }

    /**
     * 创建订单类
     * 
     * @param proData
     * @return
     */
    protected Order createOrder(ProjectdetailData proData) {

        Order order = new Order();
        order.setProjectid(proData.getProjectId());
        order.setProjectname(proData.getName());
        order.setProject_yield(proData.getYield() + proData.getAwardYield());
        order.setRecyle(proData.getPeriod());
        order.setRepaymenttype(proData.getRepayTypeName());
        order.setStartrepytime(proData.getEndInterestDate());
        order.setStartyidtime(proData.getStartInterestDate());
        order.setCaninverst(Double.parseDouble(proData.getRemainAmount()));
        order.setpType(proData.getpType());
        order.setMinInvest(proData.getMinInvest());
        order.setMaxInvest(proData.getMaxInvest());
        order.setType(proData.getType());
        order.setMode(proData.getMode());
        return order;
    }

    /**
     * 开通三方
     */
    public void openpayment() {
        params.clear();
        params.put("token", getToken());
        getDate(params, Constants.REGISTHF, handler, OPENPAYMENTSUCCES, OPENPAYMENTFAIL, true,
            true, false);
    }

    /**
     * 获取项目详情
     */
    public void getProjectDetail(String type, String mode, String projectId) {
        params.clear();
        params.put("projectId", projectId);
        params.put("type", type);
        params.put("mode", mode);
        params.put("token", getToken());
        getDate(params, Constants.PROJECTINFOQUERY, handler, GETDETAILSUCCES, GETDETAILFAIL, true,
            true, true);
    }

    public void setDialogSize() {
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        WindowManager.LayoutParams p = getWindow().getAttributes(); // 获取对话框当前的参数值
        p.width = (int) (d.getWidth() * 0.9);
        p.height = (int) (d.getHeight() * 0.8);
        getWindow().setAttributes(p);
    }

    public void initSetting() {
        if (wv_dialog != null) {
            Jpushbean2 jpushbean2 = (Jpushbean2) getIntent().getSerializableExtra("PUSH");

            String url = "";
            if (jpushbean2 != null && !StringUtils.isEmpty(jpushbean2.getTarget())) {
                url = jpushbean2.getTarget();
            } else {
                url = "http://www.twotiger.com";
            }
            //            wv_dialog.loadUrl("file:///android_asset/test.html"); 
            wv_dialog.loadUrl(url);

            WebSettings mWebSettings = wv_dialog.getSettings();
            mWebSettings.setJavaScriptEnabled(true);
            String appCachePath = getCacheDir().getAbsolutePath();
            mWebSettings.setAppCacheEnabled(true);
            mWebSettings.setDefaultTextEncodingName("UTF-8");
            mWebSettings.setAppCachePath(appCachePath);
            mWebSettings.setAppCacheMaxSize(8 * 1024 * 1024);
            mWebSettings.setAllowFileAccess(true);
            mWebSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
            if (android.os.Build.VERSION.SDK_INT >= 11) {
                mWebSettings.setDisplayZoomControls(false);
            }
            mWebSettings.setBuiltInZoomControls(false);
            mWebSettings.setUseWideViewPort(false);
            mWebSettings.setLoadWithOverviewMode(true);
            mWebSettings.setSupportZoom(true);
            String ua = Tools.getUserAgent(mContext);
            mWebSettings.setUserAgentString(ua);
            MyWebChromeClient myWebChromeClient = new MyWebChromeClient();
            new MobclickAgentJSInterface(this, wv_dialog, myWebChromeClient);
            wv_dialog.setWebChromeClient(myWebChromeClient);
            wv_dialog.setWebViewClient(new NewsClient());

            wv_dialog.addJavascriptInterface(new JavaScriptInterfaceForDialog(wv_dialog,
                WebViewDialogPage.this, handler), JavaScriptInterface.name());

        }
    }

    @Override
    protected void processLogic() {
        params = getParm();
        isFinish = false;
        errorHtml = "<html><body><h1>Page not find!</h1><h2>load failure</h2></body></html>";
        setDialogSize();
        initSetting();

        LogUtil.info("Registration ID:" + JPushInterface.getRegistrationID(mContext));
    }

    @Override
    protected void findViewById(View view) {
        wv_dialog = (CusWebView) view.findViewById(R.id.wv_dialog);
        wv_dialog.setRadius(15); //设置圆角弧度

        web_dialog_progressbar = (ProgressBar) view.findViewById(R.id.web_dialog_progressbar);
        btn_finish = (Button) view.findViewById(R.id.btn_finish);

    }

    @Override
    protected View loadViewLayout(LayoutInflater inflater) {
        View contactsLayout = inflater.inflate(R.layout.dialog_web_view_page, null);
        return contactsLayout;
    }

    @Override
    protected void onBackPress() {
        try {
            //            if (wv_dialog.canGoBack()) {
            //                wv_dialog.goBack();
            //                return;
            //            }
            finish();
            overridePendingTransition(R.anim.fade_in_anim, R.anim.fade_out_anim);
        } catch (Exception e) {
            LogUtil.info(String.valueOf(e.getMessage()));
        }
    }

    public class MyWebChromeClient extends WebChromeClient {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            return super.onJsAlert(view, url, message, result);
        }

        Dialog loadDataDialog = null;

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            //          if (newProgress == 100) {
            //          web_dialog_progressbar.setVisibility(View.GONE);
            //      } else {
            //          web_dialog_progressbar.setVisibility(View.VISIBLE);
            //          web_dialog_progressbar.setProgress(newProgress);
            //      }
            if (newProgress == 100) {
                PromptManager.closeLoadDataDialog(loadDataDialog);
            } else {
                if (loadDataDialog == null) {
                    loadDataDialog = PromptManager.showLoadDataDialog(mContext, "正在加载...");
                }
            }
        }
    }

    class NewsClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            LogUtil.info(WebViewPage.class, "页面开始的地址" + url);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description,
                                    String failingUrl) {
            view.loadData(errorHtml, "text/html; charset=UTF-8", null);//load失败，默认load本地HTML页面
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, final String url) {

            return false;
        }
    }

}
